﻿using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using RoketSolutions.SP2010.Infrostructure.Common.Extensions;
using System.Linq;

namespace RoketSolutions.SP2010.Infrostructure.UI.Controls
{
    public class UserControlBase : UserControl
    {
        protected void BindDropDown(DropDownList control, IEnumerable data, string textField, string valueField, object selectedValue)
        {
            if (data != null)
            {
                control.DataSource = data;
                if (!textField.IsNullOrEmpty())
                {
                    control.DataTextField = textField;
                }
                if (!valueField.IsNullOrEmpty())
                {
                    control.DataValueField = valueField;
                }
                control.DataBind();
            }
            if (selectedValue != null)
            {
                var value = selectedValue.ToString();
                var targetItem = control.Items.Cast<ListItem>().FirstOrDefault(item => item.Value.EqualByContent(value));
                if (targetItem != null)
                {
                    control.ClearSelection();
                    targetItem.Selected = true;
                }
            }
        }

        protected void BindPeopleEditor(PeopleEditor control, params string[] principalNames)
        {
            var pickerEntities = new ArrayList();
            foreach (var principalName in principalNames)
            {
                var entity = control.ValidateEntity(new PickerEntity{Key = principalName});
                if (entity != null)
                    pickerEntities.Add(entity);
            }
            control.UpdateEntities(pickerEntities);
        }

    }
}